package com.niepan.common.utils.minio;

import cn.hutool.core.util.StrUtil;
import com.niepan.modules.zhinenganjianback.dao.DeviceManagerDao;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author: liuchenyu
 * @date: 2023/7/31
 */

@Data
@Component
public class MinIOUtil {
//    @Value("${minio.address}")
    private String address;
//    @Value("${minio.accessKey}")
    private String accessKey;
//    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Autowired
    private DeviceManagerDao deviceManagerDao;

    private MinioClient minioClient = null;


    public MinioClient getMinioClient() {
        try {
            if (minioClient == null) {
                synchronized (MinIOUtil.class) {
                    if (minioClient == null) {
                        Map<String,Object> requestURL = deviceManagerDao.getRequestURL();
                        accessKey = (String) requestURL.get("access_key");
                        secretKey = (String) requestURL.get("secret_key");
                        address = "http://" + (String) requestURL.get("gkj_ip") + ":9000";
                        minioClient = new MinioClient(address, accessKey, secretKey);
                    }
                }
            }
            return minioClient;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    public boolean bucketExists(String bucketName) {
        boolean flag = false;
        this.getMinioClient();
        try {
            flag = this.minioClient.bucketExists(bucketName);
            if (flag) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    public boolean makeBucket(String bucketName) {
        this.getMinioClient();
        try {
            boolean flag = bucketExists(bucketName);
            //存储桶不存在则创建存储桶
            if (!flag) {
                minioClient.makeBucket(bucketName);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }



    /**
     * 上传文件
     *
     * @param file 上传文件
     * @return 成功则返回文件名，失败返回空
     */
    public String uploadFile(MultipartFile file,String fileName) {
        this.getMinioClient();
        //创建存储桶
        boolean createFlag = makeBucket(bucketName);
        //创建存储桶失败
        if (createFlag == false) {
            return "";
        }
        try {
            PutObjectOptions putObjectOptions = new PutObjectOptions(file.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
            putObjectOptions.setContentType(file.getContentType());
            String originalFilename = file.getOriginalFilename();
            int pointIndex = originalFilename.lastIndexOf(".");
            //得到文件流
            InputStream inputStream = file.getInputStream();
            //保证文件不重名(并且没有特殊字符)
//            String fileName = bucketName+ DateUtil.format(new Date(), "_yyyyMMddHHmmss") + (pointIndex > -1 ? originalFilename.substring(pointIndex) : "");
            minioClient.putObject(bucketName, fileName, inputStream, putObjectOptions);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 下载文件
     *
     * @param originalName 文件路径
     */
    public InputStream downloadFile(String originalName, HttpServletResponse response) {
        this.getMinioClient();
        try {
            InputStream file = minioClient.getObject(bucketName, originalName);
            String filename = new String(originalName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StrUtil.isNotBlank(originalName)) {
                filename = originalName;
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = file.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            file.close();
            servletOutputStream.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除文件
     *
     * @param fileName 文件路径
     * @return
     */
    public boolean deleteFile(String fileName) {
        this.getMinioClient();
        try {
            minioClient.removeObject(bucketName, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 得到指定文件的InputStream
     *
     * @param originalName 文件路径
     * @return
     */
    public InputStream getObject(String originalName) {
        this.getMinioClient();
        try {
            return minioClient.getObject(bucketName, originalName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据文件路径得到预览文件绝对地址
     * 返回的地址前端能够直接展示出来
     *
     * @param fileName    文件路径
     * @return
     */
    public String getPreviewFileUrl(String fileName) {
        this.getMinioClient();
        try {
            return minioClient.presignedGetObject(bucketName,fileName);
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }
}
